package cn.sylinx.hbatis.ext.mirage.spi;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;

import cn.sylinx.hbatis.ext.mirage.MirageService;

public final class MirageServiceManager {

	private static MirageService mirageService;

	private static ReentrantLock lock = new ReentrantLock();

	public static MirageService getMirageService() {

		if (mirageService != null) {
			return mirageService;
		}

		// 加載MirageService
		loadMirageService();

		return mirageService;

	}

	private static void loadMirageService() {

		try {

			lock.lock();

			if (mirageService == null) {

				ServiceLoader<MirageService> sl = ServiceLoader.load(MirageService.class);
				Iterator<MirageService> it = sl.iterator();
				mirageService = it.hasNext() ? it.next() : null;
			}

		} finally {
			lock.unlock();
		}

	}

}
